﻿
CREATE PROCEDURE [dbo].[GetNextBarCode] (
	@NextBarCode char(12) OUTPUT
)
AS
BEGIN
	DECLARE @intNextBarNumber int, @intDepartmentId int, @strDepNmbr varchar(3)
	DECLARE @tmp char(12), @flag bit
	SET NOCOUNT ON;

UPDATE PR.DepartmentOptions SET @intNextBarNumber = NextBarCode, 
NextBarCode = @intNextBarNumber + 1,
@strDepNmbr = cast(DepartmentId as varchar(3))

SELECT @NextBarCode = cast(@intNextBarNumber as varchar(8)),
@strDepNmbr = Replicate('0', 3 - len(@strDepNmbr)) + @strDepNmbr

SET @NextBarCode = '2' + @strDepNmbr + Replicate('0', 8 - len(@NextBarCode)) + @NextBarCode

WHILE(EXISTS(select * from CD.Parties where BarCode = @NextBarCode))
		BEGIN
			UPDATE PR.DepartmentOptions SET @intNextBarNumber = NextBarCode, 
			NextBarCode = @intNextBarNumber + 1,
			@strDepNmbr = cast(DepartmentId as varchar(3))
			SELECT @NextBarCode = cast(@intNextBarNumber as varchar(8)),
			@strDepNmbr = Replicate('0', 3 - len(@strDepNmbr)) + @strDepNmbr
			SET @NextBarCode = '2' + @strDepNmbr + Replicate('0', 8 - len(@NextBarCode)) + @NextBarCode
			
		END
	
RETURN 0
END


